package com.blockmeta.bbs.overallserviceapplication.activity.login;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.pojo.LoginPOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.R2;
import com.blockmeta.bbs.overallserviceapplication.net.SmsEcodeHelper;
import com.blockmeta.bbs.overallserviceapplication.net.api.NetApi;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;


import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by author on 2018/2/7.
 */
@Route(path = RouterPath.BIND_ACCOUNT_PHONE_ACTIVITY)
public class BindAcountPhoneActivity extends BaseActivity {
    @BindView(R2.id.iv_head_portrait)
    ImageView mIvHeadPortrait;
    @BindView(R2.id.edit_phone_number)
    EditText mEditPhoneNumber;
    @BindView(R2.id.btn_verification_code)
    Button mBtnVerificationCode;
    @BindView(R2.id.edit_verification_code)
    EditText mEditVerificationCode;
    @BindView(R2.id.voice_code)
    LinearLayout voiceCode;
    @BindView(R2.id.voice_code_tv)
    LinearLayout voiceCodeTv;
    @BindView(R2.id.tv_bind_switch)
    TextView mTvBindSwitch;
    @BindView(R2.id.btn_postpone)
    Button mBtnPostpone;

    private Context mContext;
    private SmsEcodeHelper mHelper;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        mContext = BindAcountPhoneActivity.this;
        return LayoutInflater.from(mContext).inflate(R.layout.activity_bind_acount_phone, null);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Glide.with(this).load(AccountHelper.getUserPhonePOJO().getLogo()).placeholder(R.mipmap.ic_launcher).into(mIvHeadPortrait);//设置头像
        mHelper = new SmsEcodeHelper(mContext, mBtnVerificationCode);
    }

    @OnClick({R2.id.btn_verification_code, R2.id.btn_bind, R2.id.tv_bind_switch, R2.id.btn_postpone, R2.id.voice_code})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_verification_code) {
            getEcode();

        } else if (i == R.id.btn_bind) {
            String phone = mEditPhoneNumber.getText().toString();
            String code = mEditVerificationCode.getText().toString();
            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code)) {
                ToastUtil.show(mContext, "输入的内容不能为空");
            } else {
                BindOrPostpone(phone, code);
            }

        } else if (i == R.id.tv_bind_switch) {
        } else if (i == R.id.btn_postpone) {
            finish();

        } else if (i == R.id.voice_code) {
            sendVoiceCode();
        }
    }

    /**
     * 绑定手机或者推迟绑定，
     *
     * @param phone
     * @param code
     */
    private void BindOrPostpone(String phone, String code) {
        HashMap<String, String> checkMap = new HashMap<>();
        checkMap.put("user_name", AccountHelper.getUserPhonePOJO().getUserName());
        checkMap.put("mobile", phone);
        checkMap.put("code", code);
        RetrofitFactory.getRootRetrofit().create(NetApi.SocialBind.class)
                .bindSocial(RequestBody.create(NetApi.sMediaType, new Gson().toJson(checkMap)))
                .compose(this.<BaseCodeResponse<LoginPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<LoginPOJO>>rxSchedulerHelper())
                .compose(RxUtil.<LoginPOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<LoginPOJO>(mContext) {
                    @Override
                    public void onNext(LoginPOJO loginPOJO) {
                        UserPhonePOJO userPhonePOJO = AccountHelper.getUserPhonePOJO();
                        userPhonePOJO.setMobile(phone);
                        AccountHelper.setUserPhonePOJO(userPhonePOJO);
                        finish();
                    }
                });

    }

    private void getEcode() {
        if (mEditPhoneNumber.getText().toString().length() != 11) {
            ToastUtil.show(mContext,"手机号码格式错误");
        } else {
            HashMap<String, String> ecodeMap = new HashMap<>();
            ecodeMap.put("mobile", mEditPhoneNumber.getText().toString());
            mHelper.DealWithEcode(ecodeMap);
            mHelper.setCount(new SmsEcodeHelper.CountDownTimerCallBack() {
                @Override
                public void countdowncallback(CountDownTimer countDownTimer) {
                    countDownTimer.cancel();
                    countDownTimer.start();
                }
            });
            mHelper.setTimeEquals(new SmsEcodeHelper.TimeEquals() {
                @Override
                public void timeequals(int time) {
                    if (time == 45) {
                        if (voiceCodeTv!=null){
                            voiceCodeTv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 发送语音验证码
     * 在发送短信验证码之后大概10秒钟之后
     */
    private void sendVoiceCode() {
        if (mEditPhoneNumber.getText().toString().length() != 11) {
            ToastUtil.show(mContext,"手机号码格式错误");
        } else {
            HashMap<String, String> ecodeMap = new HashMap<>();
            ecodeMap.put("mobile", mEditPhoneNumber.getText().toString());
            ecodeMap.put("type_id", "2");
            mHelper.DealWithEcode(ecodeMap);
            mHelper.setCount(new SmsEcodeHelper.CountDownTimerCallBack() {
                @Override
                public void countdowncallback(CountDownTimer countDownTimer) {
                    countDownTimer.cancel();
                    countDownTimer.start();
                }
            });
            mHelper.setTimeEquals(new SmsEcodeHelper.TimeEquals() {
                @Override
                public void timeequals(int time) {
                    if (voiceCode != null) {
                        if (time < 5) {
                            voiceCode.setClickable(true);
                        } else {
                            voiceCode.setClickable(false);
                        }
                    }
                }
            });

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHelper!=null){
            mHelper.releaseCountDown();
        }
    }
}
